import axios from "axios";
import router from "@/router";
import store from "@/store";
import { message } from "ant-design-vue";
import { getToken } from "@/utils/token";
import qs from "qs";

// 测试的时候会用到~~存在base-url的访问绝对路径获取数据
const baseUrl = sessionStorage.getItem("zxd-base-url");
// 创建 axios 实例
const service = axios.create({
  timeout: 60000, // 请求超时时间
  baseURL: baseUrl || "/api"
});
// request请求拦截器
service.interceptors.request.use(
  config => {
    // 请求get的数组统一使用repeat
    config.paramsSerializer = params => {
      return qs.stringify(params, { arrayFormat: "repeat" });
    };
    // 设置token
    const token = getToken();
    if (token) {
      config.headers["token"] = token;
    }
    return config;
  },
  error => {
    return Promise.resolve(error);
  }
);

// response响应拦截器
service.interceptors.response.use(
  response => {
    if (response.data.status === 200 || response.data.code === 200) {
      if (response.data.privs !== null && response.data.privs.length > 0) {
        //并不是每个接口都返回privs数据，目前是菜单接口才有
        store.commit("setPermissionList", response.data.privs);
      }
      return response.data;
      // return response.data
    } else if (response.data.status === 401) {
      router.push("/user/login");
    } else {
      message.error(response.data.message || response.data.data || "未知错误");
    }
    return Promise.reject(response);
  },
  error => {
    message.error(
      error.response.data.message || error.response.data.data || "未知错误"
    );
    return Promise.reject(error);
  }
);

export default service;
